package com.beeantec.jnrerc.modules.course.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beeantec.jnrerc.core.api.ApiRest;
import com.beeantec.jnrerc.core.api.controller.BaseController;
import com.beeantec.jnrerc.core.api.dto.PagingReqDTO;
import com.beeantec.jnrerc.core.constants.Constant;
import com.beeantec.jnrerc.core.enums.DynamicEnum;
import com.beeantec.jnrerc.core.enums.MediaTypeEnum;
import com.beeantec.jnrerc.core.utils.SystemUtil;
import com.beeantec.jnrerc.dto.CourseCateGoryEditDTO;
import com.beeantec.jnrerc.dto.CourseDTO;
import com.beeantec.jnrerc.dto.MemberVo;
import com.beeantec.jnrerc.dto.request.CourseListReqDTO;
import com.beeantec.jnrerc.dto.request.CourseReqDTO;
import com.beeantec.jnrerc.dto.CourseSignDTO;
import com.beeantec.jnrerc.dto.request.CourseUpdateDTO;
import com.beeantec.jnrerc.dto.response.CourseInfoDTO;
import com.beeantec.jnrerc.entity.*;
import com.beeantec.jnrerc.modules.course.service.*;
import com.beeantec.jnrerc.modules.member.service.DynamicService;
import com.beeantec.jnrerc.modules.member.service.GrowRecordService;
import com.beeantec.jnrerc.modules.member.service.MemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.websocket.server.PathParam;
import java.io.File;
import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;

@Api(tags={"课程"})
@RestController
@RequestMapping("/api/course")
public class CourseController extends BaseController {


    @Autowired
    CourseService courseService;

    @Autowired
    CourseMemberStudyService courseMemberStudyService;

    @Autowired
    CourseChapterPeriodService courseChapterPeriodService;

    @Autowired
    CourseChapterService courseChapterService;

    @Autowired
    CourseMemberStudyLogService memberStudyLogService;

    @Autowired
    CourseVideoService courseVideoService;


    @Autowired
    MemberService memberService;

    @Autowired
    GrowRecordService growRecordService;

    @Autowired
    CourseMemberStudyLogService studyLogService;

    @Autowired
    DynamicService dynamicService;

    /**
     * 课程信息列表接口
     *
     * @param reqDTO
     * @return
     * @author anthony
     */
    @ApiOperation(value = "课程列表接口", notes = "根据条件分页列出课程信息")
    @RequestMapping(value = "/list", method = RequestMethod.POST)

    public ApiRest<IPage<Course>> list(@RequestBody CourseListReqDTO reqDTO) {

        IPage<Course> courseIPage;

        if (ObjectUtil.isEmpty(reqDTO.getKeyWord())){
            //分页查询并转换
            QueryWrapper<Course> courseDTOQueryWrapper = new QueryWrapper<>();
            courseDTOQueryWrapper.lambda().eq(Course::getCategoryId1,reqDTO.getCategoryId());
            Page<Course> page = new Page<>(reqDTO.getPage(), reqDTO.getSize());
            courseIPage= courseService.getBaseMapper().selectPage(page,courseDTOQueryWrapper);
        }else {
            //分页查询并转换
            QueryWrapper<Course> courseDTOQueryWrapper = new QueryWrapper<>();
            courseDTOQueryWrapper.lambda().like(Course::getCourseName,reqDTO.getKeyWord());
            Page<Course> page = new Page<>(reqDTO.getPage(), reqDTO.getSize());
            courseIPage= courseService.getBaseMapper().selectPage(page,courseDTOQueryWrapper);
        }

        return super.success(courseIPage);
    }



    /**
     * 课程信息列表接口
     *
     * @return
     * @author anthony
     */
    @ApiOperation(value = "课程列表接口", notes = "根据条件分页列出课程信息")
    @RequestMapping(value = "/hotlist", method = RequestMethod.POST)

    public ApiRest<List<Course>> hotList() {
            List<Course>  courseList = new ArrayList<>();
            QueryWrapper<Course> courseDTOQueryWrapper = new QueryWrapper<>();
            courseDTOQueryWrapper.lambda().orderByDesc(Course::getCountStudy);
            courseList= courseService.list(courseDTOQueryWrapper);
        return super.success(courseList);
    }

    /**
     * 课程详情接口
     *
     * @param courseId
     * @return
     */
    @ApiOperation(value = "课程详情接口", notes = "根据课程ID获取课程信息")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public ApiRest<CourseInfoDTO> info(@RequestHeader("token")String token,@RequestParam Long courseId) {
        CourseInfoDTO courseInfoDTO =courseService.info(token,courseId);
        return success(courseInfoDTO);
    }


    /**
     * 创建课程
     *
     * @param course
     * @return
     */
    @ApiOperation(value = "添加/修改课程", notes = "添加课程")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ApiRest<Boolean> add(@RequestBody Course course) {
        Boolean result =courseService.save(course);
        MemberDynamic memberDynamic = new MemberDynamic();
        memberDynamic.setMemberId(0L);
        memberDynamic.setCreateTime(new Date());
        memberDynamic.setTitle("我发布了一个课程，快来学习吧！");
        memberDynamic.setType(DynamicEnum.COURSE.getCode());
        memberDynamic.setItemId(course.getId());
        dynamicService.saveOrUpdate(memberDynamic);
        return success(result);
    }


    /**
     * 编辑课程
     *
     * @author anthony
     */
    @ApiOperation(value = "编辑课程", notes = "编辑课程")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public ApiRest<Boolean> edit(@RequestBody CourseUpdateDTO courseUpdateDTO) {
        Course course = courseService.getById(courseUpdateDTO.getCourseId());
        course.setCourseName(courseUpdateDTO.getCourseName());
        course.setCourseLogo(courseUpdateDTO.getCourseCover());
        return success(courseService.saveOrUpdate(course));
    }


    /**
     * 删除课程
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除课程", notes = "删除课程")
    @RequestMapping(value = "/removeCourse", method = RequestMethod.GET)
    public ApiRest<String> removeCourse(@RequestParam("courseId") Long id) {
        if (!courseService.removeById(id)){
            return failure("删除课程失败");
        }
        QueryWrapper<CourseChapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.lambda().eq(CourseChapter::getCourseId,id);
       courseChapterService.remove(chapterQueryWrapper);
       QueryWrapper<CourseChapterPeriod> chapterPeriodQueryWrapper = new QueryWrapper<>();
       chapterPeriodQueryWrapper.lambda().eq(CourseChapterPeriod::getCourseId,id);
      courseChapterPeriodService.remove(chapterPeriodQueryWrapper);
        return success("删除成功");
    }


    /**
     * 删除课程小节
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除课程小节", notes = "删除课程小节")
    @RequestMapping(value = "/removeChaper", method = RequestMethod.GET)
    public ApiRest<String> removeChapter(@RequestParam("courseId") Long id,@RequestParam("chapterId") Long chapterId) {
        QueryWrapper<CourseChapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.lambda().eq(CourseChapter::getCourseId,id).eq(CourseChapter::getId,chapterId);
        if (!courseChapterService.remove(chapterQueryWrapper)){
            return failure("删除课程下小节失败");
        }
        QueryWrapper<CourseChapterPeriod> chapterPeriodQueryWrapper = new QueryWrapper<>();
        chapterPeriodQueryWrapper.lambda().eq(CourseChapterPeriod::getCourseId,id).eq(CourseChapterPeriod::getChapterId,chapterId);
        courseChapterPeriodService.remove(chapterPeriodQueryWrapper);
        return success("删除成功");
    }


    /**
     * 删除课时
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除课时", notes = "删除课时")
    @RequestMapping(value = "/removePeriod", method = RequestMethod.GET)
    public ApiRest<String> removeChapterPeriod(@RequestParam("courseId") Long id,@RequestParam("chapterId") Long chapterId,@RequestParam("periodId") Long periodId) {
        QueryWrapper<CourseChapterPeriod> chapterPeriodQueryWrapper = new QueryWrapper<>();
        chapterPeriodQueryWrapper.lambda().eq(CourseChapterPeriod::getCourseId,id)
                .eq(CourseChapterPeriod::getChapterId,chapterId).eq(CourseChapterPeriod::getId,periodId);
        if (!courseChapterPeriodService.remove(chapterPeriodQueryWrapper)){
            return failure("删除课时失败");
        }
        return success("删除成功");
    }




    /**
     * 创建课程小节
     *
     * @param courseChapter
     * @return
     */
    @ApiOperation(value = "添加课程小节", notes = "添加课程小节")
    @RequestMapping(value = "/add/chapter", method = RequestMethod.POST)
    public ApiRest<Boolean> addChapter(@RequestBody CourseChapter courseChapter) {
        Boolean result =courseChapterService.save(courseChapter);
        return success(result);
    }



    /**
     * 获取课程小节
     *
     * @param courseId
     * @return
     */
    @ApiOperation(value = "获取课程小节", notes = "获取课程小节")
    @RequestMapping(value = "/get/chapters", method = RequestMethod.GET)
    public ApiRest<List<CourseChapter>> get(@RequestParam("courseId") Long courseId) {
        List<CourseChapter> courseChapterList = new ArrayList<>();
        QueryWrapper<CourseChapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CourseChapter::getCourseId,courseId);
        courseChapterList =courseChapterService.list(queryWrapper);
        return success(courseChapterList);
    }


    /**
     * 获取课程小节课时
     *
     * @param courseId
     * @return
     */
    @ApiOperation(value = "获取课程小节课时", notes = "获取课程小节课时")
    @RequestMapping(value = "/get/chapter/periods", method = RequestMethod.GET)
    public ApiRest<List<CourseChapterPeriod>> get(@RequestParam("courseId") Long courseId,@RequestParam("chapterId") Long chapterId) {
        List<CourseChapterPeriod> courseChapterPeriods = new ArrayList<>();
        QueryWrapper<CourseChapterPeriod> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CourseChapterPeriod::getCourseId,courseId)
        .eq(CourseChapterPeriod::getChapterId,chapterId);
        courseChapterPeriods =courseChapterPeriodService.list(queryWrapper);
        return success(courseChapterPeriods);
    }



    /**
     * 获取课时详情
     *
     * @return
     */
    @ApiOperation(value = "获取课时详情", notes = "获取课时详情")
    @RequestMapping(value = "/get/perioddetail", method = RequestMethod.GET)
    public ApiRest<CourseChapterPeriod> getPeriodDetail(@RequestParam("courseId") Long courseId,@RequestParam("chapterId") Long chapterId,@RequestParam("periodId") Long periodId) {
        QueryWrapper<CourseChapterPeriod> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CourseChapterPeriod::getCourseId,courseId)
                .eq(CourseChapterPeriod::getChapterId,chapterId).eq(CourseChapterPeriod::getId,periodId);
        CourseChapterPeriod courseChapterPeriod =courseChapterPeriodService.getOne(queryWrapper);
        return success(courseChapterPeriod);
    }


    /**
     * 获取课节详情
     *
     * @return
     */
    @ApiOperation(value = "获取课节详情", notes = "获取课节详情")
    @RequestMapping(value = "/get/chapterdetail", method = RequestMethod.GET)
    public ApiRest<CourseChapter> getChapterDetail(@RequestParam("courseId") Long courseId,@RequestParam("chapterId") Long chapterId) {
        QueryWrapper<CourseChapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CourseChapter::getCourseId,courseId)
                .eq(CourseChapter::getId,chapterId);
        CourseChapter courseChapter =courseChapterService.getOne(queryWrapper);
        return success(courseChapter);
    }


    /**
     * 编辑课节
     *
     * @return
     */
    @ApiOperation(value = "编辑课节", notes = "编辑课节")
    @RequestMapping(value = "/edit/chapter", method = RequestMethod.POST)
    public ApiRest<String> editChapter(@RequestBody CourseChapter courseChapter) {
       if (courseChapterService.saveOrUpdate(courseChapter)){
           return success("编辑成功");
       }
        return failure("编辑失败");
    }


    /**
     * 编辑课时
     *
     * @return
     */
    @ApiOperation(value = "编辑课时", notes = "编辑课时")
    @RequestMapping(value = "/edit/period", method = RequestMethod.POST)
    public ApiRest<String> editPeriod(@RequestBody CourseChapterPeriod courseChapterPeriod) {
        if (courseChapterPeriodService.saveOrUpdate(courseChapterPeriod)){
            return success("编辑成功");
        }
        return failure("编辑失败");
    }




    /**
     * 添加课时
     *
     * @return
     */
    @ApiOperation(value = "添加课时", notes = "添加课时")
    @RequestMapping(value = "/add/chapter/period", method = RequestMethod.POST)
    public ApiRest<String> addPeriod(@RequestParam(value = "file", required = false) MultipartFile file
            , @RequestParam("courseId") Long courseId,@RequestParam("chapterId") Long chapterId,@RequestParam("fTime") Integer fTime
    ,@RequestParam("rType") Integer rType,@RequestParam("rCount") Integer rCount,@RequestParam("pContent") String pContent,@RequestParam("periodName") String periodName,@RequestParam("periodDesc") String periodDesc) {
        return  uploadVideo(file,courseId,chapterId,fTime,rType,rCount,pContent, periodName, periodDesc);
    }




    /**
     * 领取奖励
     *
     * @return
     */
    @ApiOperation(value = "领取奖励", notes = "领取奖励")
    @RequestMapping(value = "/receive", method = RequestMethod.GET)
    public ApiRest<String> receive(@RequestHeader("token") String token,@RequestParam("pId") Long periodId){
        MemberVo memberVo = memberService.token(token);
        if (null==memberVo){
            return failure("用户不存在");
        }
        Member member = memberService.getById(memberVo.getMemberId());
       CourseChapterPeriod courseChapterPeriod = courseChapterPeriodService.getById(periodId);
        QueryWrapper<CourseMemberStudyLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CourseMemberStudyLog::getCourseId,courseChapterPeriod.getCourseId())
                .eq(CourseMemberStudyLog::getPeriodId,courseChapterPeriod.getId())
                .eq(CourseMemberStudyLog::getMemberId,member.getMemberId());
        CourseMemberStudyLog memberStudyLog = studyLogService.getOne(queryWrapper);
        if (null==memberStudyLog){
            return failure("暂无该学习记录");
        }
        memberStudyLog.setPeriodState(2);
        studyLogService.saveOrUpdate(memberStudyLog);
        GrowRecord growRecord = new GrowRecord();
       if (courseChapterPeriod.getRType()==0){
           growRecord.setDes("学习课程，获得积分");
           int ig = member.getIntegral()+ courseChapterPeriod.getRCount();
           member.setIntegral(ig);
       }else if (courseChapterPeriod.getRType()==1){
           growRecord.setDes("学习课程，获得魅力值");
           int ig = member.getCharm()+ courseChapterPeriod.getRCount();
           member.setCharm(ig);
       }else if (courseChapterPeriod.getRType()==2){
           growRecord.setDes("学习课程，获得经验值");
           int ig = member.getExp()+ courseChapterPeriod.getRCount();
           member.setExp(ig);
       }
       boolean r =  memberService.saveOrUpdate(member);
       if (!r){
           return failure("积分累计失败");
       }
        boolean cr =  courseChapterPeriodService.saveOrUpdate(courseChapterPeriod);
       if (!cr){
           return failure("课时状态变更失败");
       }

       growRecord.setCount(courseChapterPeriod.getRCount());
       growRecord.setCreateTime(new Date());
       growRecord.setType(courseChapterPeriod.getRType());
       growRecord.setMemberId(member.getMemberId().longValue());
      boolean gr = growRecordService.save(growRecord);
      if (!gr){
          return failure("添加用户成长记录失败");
      }
        return  success("领取成功");
    }





    /**
     * 课程学习签到接口
     *
     * @param authCourseSignBO
     * @return
     */
    @ApiOperation(value = "课程学习签到接口", notes = "用户学习课程签到")
    @RequestMapping(value = "/sign", method = RequestMethod.POST)
    public ApiRest<String> sign(@RequestBody CourseSignDTO authCourseSignBO) {
        if (ObjectUtil.isNull(authCourseSignBO.getUserNo())) {
            return super.failure("memberId不能为空");
        }
        if (ObjectUtil.isNull(authCourseSignBO.getPeriodId())) {
            return super.failure("periodId不能为空");
        }

        // 课时信息
        QueryWrapper<CourseChapterPeriod> chapterPeriodQueryWrapper = new QueryWrapper<>();
        chapterPeriodQueryWrapper.lambda().eq(CourseChapterPeriod::getChapterId,authCourseSignBO.getChapterId())
                .eq(CourseChapterPeriod::getCourseId,authCourseSignBO.getCourseId())
                .eq(CourseChapterPeriod::getId,authCourseSignBO.getPeriodId());
        CourseChapterPeriod courseChapterPeriod = courseChapterPeriodService.getOne(chapterPeriodQueryWrapper);
        if (StringUtils.isEmpty(courseChapterPeriod)) {
            return super.failure("找不到课时信息");
        }
        // 章节信息
        QueryWrapper<CourseChapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.lambda().eq(CourseChapter::getId,authCourseSignBO.getChapterId())
                .eq(CourseChapter::getCourseId,authCourseSignBO.getCourseId());
        CourseChapter courseChapter = courseChapterService.getOne(chapterQueryWrapper);
        if (ObjectUtil.isNull(courseChapter)) {
            return super.failure("找不到章节信息");
        }
        // 课程信息
        Course course = courseService.getById(courseChapterPeriod.getCourseId());
        if (StringUtils.isEmpty(course)) {
            return super.failure("找不到课程信息");
        }
//        courseChapterPeriod.setStatusId(1);
//        courseChapterPeriodService.saveOrUpdate(courseChapterPeriod);
        Executors.newFixedThreadPool(50).execute(new StudyLog(authCourseSignBO, courseChapterPeriod, course, courseChapter));

        return success("");
    }

    class StudyLog implements Runnable {
        private CourseSignDTO authCourseSignBO;
        private CourseChapterPeriod courseChapterPeriod;
        private Course course;
        private CourseChapter courseChapter;

        public StudyLog(CourseSignDTO authCourseSignBO, CourseChapterPeriod courseChapterPeriod, Course course, CourseChapter courseChapter) {
            this.authCourseSignBO = authCourseSignBO;
            this.courseChapterPeriod = courseChapterPeriod;
            this.courseChapter = courseChapter;
            this.course = course;
        }

        @Override
        public void run() {
            // 更新学习人数
            updateCount(course);

            // 学习日志与统计
            studyCount(authCourseSignBO, courseChapterPeriod, course, courseChapter);
        }

        /**
         * 更新学习人数
         */
        private boolean updateCount(Course course) {
            Course record = new Course();
            record.setId(course.getId());
            record.setCountStudy(course.getCountStudy() + 1);
            return courseService.updateById(record);
        }

        private void studyCount(CourseSignDTO authCourseSignBO, CourseChapterPeriod courseChapterPeriod, Course course, CourseChapter courseChapter) {
            // 查找课程用户关联表
            QueryWrapper<CourseMemberStudy> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(CourseMemberStudy::getMemberId, authCourseSignBO.getUserNo())
            .eq(CourseMemberStudy::getCourseId, courseChapterPeriod.getCourseId());
            CourseMemberStudy courseUserStudy = courseMemberStudyService.getOne(queryWrapper);
            // 如果不存在记录
            if (null == courseUserStudy) {
                courseUserStudy = new CourseMemberStudy();
                courseUserStudy.setCourseId(course.getId());
                courseUserStudy.setMemberId(authCourseSignBO.getUserNo().intValue());
                courseUserStudy.setPeriodTotal(course.getPeriodTotal());
                courseUserStudy.setPeriodStudy(1);
                courseMemberStudyService.save(courseUserStudy);

                CourseMemberStudyLog courseUserStudyLog = new CourseMemberStudyLog();
                courseUserStudyLog.setPeriodId(courseChapterPeriod.getId());
                courseUserStudyLog.setPeriodName(courseChapterPeriod.getPeriodName());
                courseUserStudyLog.setChapterId(courseChapterPeriod.getChapterId());
                courseUserStudyLog.setChapterName(courseChapter.getChapterName());
                courseUserStudyLog.setCourseId(courseChapterPeriod.getCourseId());
                courseUserStudyLog.setCourseName(course.getCourseName());
                courseUserStudyLog.setMemberId(authCourseSignBO.getUserNo().intValue());
                courseUserStudyLog.setPeriodState(1);
                courseUserStudyLog.setCreateTime(new Date());
                memberStudyLogService.save(courseUserStudyLog);
            } else {
                QueryWrapper<CourseMemberStudyLog> logQueryWrapper = new QueryWrapper<>();
                logQueryWrapper.lambda().eq(CourseMemberStudyLog::getMemberId, authCourseSignBO.getUserNo())
                        .eq(CourseMemberStudyLog::getPeriodId, authCourseSignBO.getPeriodId())
                        .eq(CourseMemberStudyLog::getCourseId,authCourseSignBO.getCourseId())
                        .eq(CourseMemberStudyLog::getChapterId,authCourseSignBO.getChapterId());
                CourseMemberStudyLog courseMemberStudyLog = memberStudyLogService.getBaseMapper().selectOne(logQueryWrapper);
                if (courseMemberStudyLog == null) {
                    // 记录
                    courseMemberStudyLog = new CourseMemberStudyLog();
                    courseMemberStudyLog.setPeriodId(courseChapterPeriod.getId());
                    courseMemberStudyLog.setPeriodName(courseChapterPeriod.getPeriodName());
                    courseMemberStudyLog.setChapterId(courseChapterPeriod.getChapterId());
                    courseMemberStudyLog.setChapterName(courseChapter.getChapterName());
                    courseMemberStudyLog.setCourseId(courseChapterPeriod.getCourseId());
                    courseMemberStudyLog.setCourseName(course.getCourseName());
                    courseMemberStudyLog.setMemberId(authCourseSignBO.getUserNo().intValue());
                    courseMemberStudyLog.setPeriodState(1);
                    memberStudyLogService.save(courseMemberStudyLog);

                    courseUserStudy.setPeriodTotal(course.getPeriodTotal());
                    courseUserStudy.setPeriodStudy(courseUserStudy.getPeriodStudy() + 1);
                    courseMemberStudyService.updateById(courseUserStudy);
                } else {
                    courseUserStudy.setPeriodTotal(course.getPeriodTotal());
                    courseUserStudy.setPeriodStudy(courseUserStudy.getPeriodStudy() + 1);
                    courseMemberStudyService.updateById(courseUserStudy);
                }
            }
        }
    }

    /**
     * 上传视频接口
     *
     * @author anthony
     */
    public ApiRest<String> uploadVideo(MultipartFile videoFile,Long courseId,Long chapterId,Integer fTime,Integer rType,Integer rCount,String pContent,String periodName,String periodDesc) {
        // 视频上传
        if (videoFile == null &&pContent.isEmpty()) {
            return super.failure("上传失败");
        }

        CourseChapterPeriod courseChapterPeriod = new CourseChapterPeriod();
        courseChapterPeriod.setCourseId(courseId);
        courseChapterPeriod.setChapterId(chapterId);
        courseChapterPeriod.setFTime(fTime);
        courseChapterPeriod.setRType(rType);
        courseChapterPeriod.setPeriodName(periodName);
        courseChapterPeriod.setPeriodDesc(periodDesc);
        courseChapterPeriod.setRCount(rCount);
        boolean fileStatus = true;

        // 获取上传文件的原名
        if (null!=videoFile){
            String fileName = videoFile.getOriginalFilename();
            // 1、上传到本地
            File targetFile = null;

            List<String> fileVideoTypes = Arrays.asList("avi", "mp4", "flv", "mpg", "mov", "asf", "3gp", "f4v", "wmv",
                    "x-ms-wmv\n");
            List<String> fileAudioTypes = Arrays.asList("mp3");

            List<String> fileDocTypes = Arrays.asList("doc");
            for (String filetype : fileVideoTypes) {
                // 上传文件的原名+小写+后缀
                if (fileName.toLowerCase().endsWith(filetype)) {
                    fileStatus = false;
                    targetFile = new File(
                            SystemUtil.PERIOD_VIDEO_PATH + fileName);
                    targetFile.setLastModified(System.currentTimeMillis());// 设置最后修改时间
                    courseChapterPeriod.setFileUrl(Constant.BASE_SERVER+"/video/" + fileName );
                    courseChapterPeriod.setFileType(MediaTypeEnum.VIDEO.getCode());
                    break;
                }
            }
            for (String filetype : fileAudioTypes) {
                // 上传文件的原名+小写+后缀
                if (fileName.toLowerCase().endsWith(filetype)) {
                    fileStatus = false;
                    targetFile = new File(
                            SystemUtil.PERIOD_AUDIO_PATH + fileName);
                    targetFile.setLastModified(System.currentTimeMillis());// 设置最后修改时间
                    courseChapterPeriod.setFileUrl(Constant.BASE_SERVER+"/audio/" + fileName);
                    courseChapterPeriod.setFileType(MediaTypeEnum.AUDIO.getCode());
                    break;
                }
            }
            if (fileStatus) {
                return super.failure("上传的文件类型不正确");
            }
            Long videoNo = IdWorker.getId(); // 当作存储到本地的文件名，方便定时任务的处理


            // 判断文件目录是否存在，不存在就创建文件目录
            if (courseChapterPeriod.getFileType()!=MediaTypeEnum.DOC.getCode()&&!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            try {
                videoFile.transferTo(targetFile);
            } catch (Exception e) {
                return super.failure("上传文件出错，请重新上传");
            }


            courseChapterPeriod.setFileSize(targetFile.length()+"");
            // 新增课程视频表信息
            courseChapterPeriod.setFileNo(videoNo);
            courseChapterPeriod.setFileName(fileName);
        }


        if (!pContent.isEmpty()){
            fileStatus = false;
            courseChapterPeriod.setFileUrl("");
            courseChapterPeriod.setFileType(MediaTypeEnum.DOC.getCode());
            courseChapterPeriod.setPContent(pContent);
        }

        if (fileStatus) {
            return super.failure("上传的文件类型不正确");
        }

        Boolean result =courseChapterPeriodService.saveOrUpdate(courseChapterPeriod);
        if (result){
           Course course =  courseService.getById(courseId);
           if (!ObjectUtil.isNull(course)){
               Integer total = course.getPeriodTotal()+1;
               course.setPeriodTotal(total);
           }
           courseService.saveOrUpdate(course);
            return success(String.valueOf(courseChapterPeriod.getFileNo()));
        }
        return failure(String.valueOf(courseChapterPeriod.getFileNo()));
    }

}
